import sys
import os.path

from xml.dom.minidom import *
from projectInfo import *

class ProjectFileCreator(object):
  def __init__(self):
    pass

  def export(self, proj):
    if not type(proj) is ProjectInfo:
      raise Exception('proj should be a ProjectInfo object.')

    proj.dump()

    dom = Document()

    # create root node
    projElement = dom.createElement('Project')
    dom.appendChild(projElement)

    # create properties nodes
    propsElement = self.getPropertiesNode(dom, proj)
    if propsElement is None:
      raise Exception('Can not create Property element from ProjectInfo.')
    
    projElement.appendChild(propsElement)

    # create items nodes
    itemsElement = self.getItemsNode(dom, proj)
    if itemsElement is None:
      raise Exception('Can not create Items element from ProjectInfo.')
      
    projElement.appendChild(itemsElement)

    filename = os.path.normpath(proj.getPath()) + os.path.sep + proj.getName() + '.pyproj'
    if os.path.exists(filename):
      if sys.platform == '__WXGTK__':
        os.system('rm %s' % filename)
      elif sys.platform == '__WXMSW__':
        os.system('del %s' % filename)
        
    fi = open(filename, 'w')
    dom.writexml(fi, '', '  ', os.linesep)
    fi.flush()
    fi.close()

  def getPropertiesNode(self, dom, proj):
    if dom is None or proj is None:
      return None
    
    propsElement = dom.createElement('Properties')

    # Name node
    propsElement.appendChild(self.createElementWithText(dom, 'Name', proj.getName()))
    # Path node
    propsElement.appendChild(self.createElementWithText(dom, 'Path', proj.getPath()))
    # Version node
    propsElement.appendChild(self.createElementWithText(dom, 'Version', proj.getVersion()))
    # Author node
    propsElement.appendChild(self.createElementWithText(dom, 'Author', proj.getAuthor()))
    # Lisence node
    propsElement.appendChild(self.createElementWithText(dom, 'Lisence', proj.getLisence()))
    # MainScript node
    propsElement.appendChild(self.createElementWithText(dom, 'MainScript', proj.getMainScript()))
    # Description node
    propsElement.appendChild(self.createElementWithText(dom, 'Description', proj.getDescription()))
    
    return propsElement

  def getItemsNode(self, dom, parent):
    if dom is None:
      return None

    element = None
    if type(parent) is ProjectInfo:
      element = dom.createElement('Items')
    else:
      element = dom.createElement('Folder')
      element.setAttribute('name', parent.getName())

    itemlist = parent.getItems()
    for item in itemlist:
      if (item.getType() & ProjectItemType.Folder) == ProjectItemType.Folder:
        subElement = self.getItemsNode(dom, item)
        if not subElement is None:
          element.appendChild(subElement)
      elif (item.getType() & ProjectItemType.File) == ProjectItemType.File:
        subElement = dom.createElement('File')
        subElement.setAttribute('name', item.getName())
        element.appendChild(subElement)
        
    return element
                             

  def createElementWithText(self, dom, tagName, text):
    assert not dom is None    
    element = dom.createElement(tagName)
    element.appendChild(dom.createTextNode(text))
    return element
    
##################################################################################
# test code
if __name__ == '__main__':
  import sys
  import getopt
  from projectImporter import ProjectImporter
  
  def showItem(lst, lvl):
    for item in lst:
      print '%s+- %s: %s' % (' ' * lvl, item.getName(), item.getFullname())
      if len(item.getItems()) > 0:
        showItem(item.getItems(), lvl + 1)

  try:
    opts, args = getopt.getopt(sys.argv[1:], "hd:v", ["help", "path="])
  except getopt.GetoptError, err:
    print 'Get opt failed.%s%s' % (os.linesep, str(err))
    sys.exit(2)
    
  path = ''
  for opt, arg in opts:
    if opt.lower() == '--path' or opt.lower() == '--p':
      path = os.path.abspath(arg)
      print 'Source Path: %s' % path
      print '------------------------------------'

  if path == '':
    print 'Please enter a file name by \'--path=\' or \'--p\' argument.'
    
  if not os.path.exists(path):
    print 'Can not find the path: %s' % path
    sys.exit(2)
        
  importer = ProjectImporter()
  proj = importer.importFromPath('wxPyDev', path)

  print '%s: %s' % (proj.getName(), proj.getPath())
  showItem(proj.getItems(), 1)

  fileCreator = ProjectFileCreator()
  fileCreator.export(proj)
